<?php
namespace app\houtai\controller\user;
use app\houtai\controller\BaseController;
use think\Db;
use think\Paginator;
use think\paginator\driver\Bootstrap;
use think\Request;
use think\Config;

class TableController extends BaseController {
  /**
   *  @brief  : 用户管理-在线房间
   *  @return : page
   *  @details: 
   */
  public function indexAction(){
      $USER_INFO = $this->GetUserInfo();
      $CHANNELS = $this->GetAdminChannel();
      $GAME_KIND = GetGameKind();
      $a = array_values($CHANNELS);
      $b = $a[1]['ID'];
      $Channel = $this->request->param('Channel/d', $b);
      $KindID = $this->request->param('KindID/d', 0);
      $ServerID = $this->request->param('ServerID/d', 0);
      if ($ServerID != 0 && $KindID == 0) {
          $ServerID = 0;
          echo "<script>alert('未选择游戏标识,无法进行服务请求');</script>";
      }
      $param = [
          'name'   =>'GetOnlineHome',
          'channel' => $Channel,
          'KindID'  => $KindID,
          'ServerID'=> $ServerID
      ];

// //   $param = '&channel='.$Channel.'&KindID='.$KindID.'&ServerID='.$ServerID;
// //   $param = 'name=GetOnlineServer'.$param;
//      $addr = substr($Channel,1,4)+1000;
//      $html = CallGoSrv($param,$addr);//执行句柄，获取返回内容

      $html = '[{"KindID":50,"ServerID":1,"OwnerID":588,"RoomId":256983,"GameChannel":43661,"GroupID":0,"AddrIp":":1990","CreateTimer":"2019-10-15 14:43:33.4692112"},{"KindID":50,"ServerID":1,"OwnerID":589,"RoomId":143244,"GameChannel":43661,"GroupID":0,"AddrIp":":1990","CreateTimer":"2019-10-15 14:57:03.1897564"}]';
//           //////////////////////////////////////////////////////

      $out_arr = is_json($html);

      if (!empty($out_arr)) {       //判断是否json数据
          $result = json_decode($html, true);
          $num = count($result);
          $SERVERS = array_column($result,'ServerID');
          $SERVER = array_unique($SERVERS);
          $curpage = input('page') ? input('page') : 1;     //当前第x页，
          $url = url('user.table/index');
          $p = paginations($result,$curpage,1,$url);  //封装数组数据分页
          $this->assign('plistpage', $p->render());
          return $this->fetch('',[
              'list'      =>$p,
              'NUM'       =>$num,
              'CHANNELS'  =>$CHANNELS,
              'Channel'   =>$Channel,
              'GAME_KIND' =>$GAME_KIND,
              'USER_INFO' =>$USER_INFO,
              'KindID'    =>$KindID,
              'ServerID'  =>$ServerID,
              'SERVER'    =>$SERVER,
          ]);
      } else {
          return $this->fetch('',[
              'list'      =>'',
              'NUM'       =>0,
              'CHANNELS'  =>$CHANNELS,
              'Channel'   =>$Channel,
              'GAME_KIND' =>$GAME_KIND,
              'USER_INFO' =>$USER_INFO,
              'KindID'    =>$KindID,
              'ServerID'  =>$ServerID,
              'SERVER'    => '',
              'error'     => $html,
              'plistpage' =>'',
          ]);
      }
  }

    /**
     *  @brief  : 用户管理-强制解散房间
     *  @return : array
     *  @details:
     */
    public function delroomAction(){
        $chan = $this->request->param('Channel/d');
        $kind = $this->request->param('KindID/d');
        $roomid = $this->request->param('RoomID/d');
        $server = $this->request->param('ServerID/d');
//        $param = [
//            'name'   =>'StrongDeleteRoom',
//            'channel' => $chan,
//            'KindID'  => $kind,
//            'RoomID'  => $roomid,
//            'ServerID'=> $server
//        ];
//        $addr = substr($chan,1,4)+1000;
//        $html = CallGoSrv($param,$addr);//执行句柄，获取返回内容

        return result([],0,'success');
    }


  /**
   *  @brief  : 用户管理-创建房间统计
   *  @return : page
   *  @details: 
   */
  public function trendAction() {
    $conds = [];
    $order = [];
    $GAME_RECORD_TYPE = config('GAME_RECORD_TYPE');
    $CHANNELS   = $this->GetAdminChannel();
    $GAME_KIND  = GetGameKind();
    ////////////////////////////////////////////////////////////////////////////
    $type = $this->request->param('type/d', -1);
    $type = array_key_exists($type, $GAME_RECORD_TYPE) ? $type : -1;
    if ($type != -1) {
      $conds['a.RecordType'] = $type;
    }
    ////////////////////////////////////
    $Channel = $this->request->param('Channel/d', -1);
    if ($Channel > 0 && array_key_exists($Channel, $CHANNELS)) {
      $conds['e.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['e.Channel'][] = ['EQ', $Channel];
    } else {
      $conds['e.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    ////////////////////////////////////
    $KindID = $this->request->param('KindID/d', -1);
    if ($KindID > 0 && array_key_exists($KindID, $GAME_KIND)) {
      $conds['a.KindID'] = $KindID;
    }
    ////////////////////////////////////
    $time1 = $this->request->param('time1/s', '', 'trim,YmdHis2Unix');
    $time2 = $this->request->param('time2/s', '', 'trim,YmdHis2Unix');
    $time2 = ($time2 > 0 && $time2 <= time()) ? $time2 : time();
    $time1 = ($time1 > 0 && $time1 <= $time2) ? $time1 : time() - 15 * 24 * 60 * 60; // 默认半个月的数据
    $time1 = date('Y-m-d 00:00:00', $time1);
    $time2 = date('Y-m-d 23:59:59', $time2);
    $conds['a.CreateTime'] = ['BETWEEN TIME', [$time1, $time2]];
    ////////////////////////////////////////////////////////////////////////////
    $list = [];
    $sql2 = table('CYRecordDB.dbo.RecordCreateTable a', 'rydb.record')->field([
      'CONVERT(VARCHAR(10), [a].[CreateTime], 120)' => 'y',
      'COUNT(*)' => 'c',
    ])
    ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = a.UserID', 'LEFT')
    ->group('CONVERT(VARCHAR(10), [a].[CreateTime], 120)')->where($conds)->buildSql();
    // 按日期分组满足条件有几条
    $total = db('', 'rydb.record')->table("{$sql2} b")->count();
    if ($total > 0) {
      $list = table('CYRecordDB.dbo.RecordCreateTable a', 'rydb.record')->field([
        'CONVERT(VARCHAR(10), [a].[CreateTime], 120)' => 'y',
        'DATEPART(hh, [a].[CreateTime])' => 'h',
        'COUNT([a].[RecordID])' => 'c',
      ])
      ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = a.UserID', 'LEFT')
      ->group('CONVERT(VARCHAR(10), [a].[CreateTime], 120), DATEPART(hh, [a].[CreateTime])')
      ->where($conds)->order(['y' => 'DESC', 'h'])->select(); // 按日期小时分组
    }
    
    $path = Request::instance()->baseUrl();
    $page = new \org\dtcms($list, $total <= 0 ? 1 : $total, 1, $total, false, ['path' => $path]);
    ////////////////////////////////////////////////////////////////////////////
    $tree = [];
    $totalALL = 0;
    foreach($list as $a) {
      $y = $a['y'];
      if (!isset($tree[$y])) {
        $tree[$y] = ['total' => 0, 'child' => []];
      }
      $tree[$y]['total'] += $a['c'];
      $tree[$y]['child'][$a['h']] = $a;
      $totalALL += $a['c'];
    }
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
        'Channel' => $Channel,
        'KindID'  => $KindID,
        'type'    => $type,
        'time1'   => $time1,
        'time2'   => $time2,
        'tree'    => $tree,
        'page'    => $page,
        'info'    => [
            'AvgDay'   => (count($tree) <= 0 ? 0 : $totalALL / count($tree)),
            'TotalDay' => count($tree),
            'TotalALL' => $totalALL,
        ],
      'CHANNELS'  => $CHANNELS,
      'GAME_KIND' => $GAME_KIND,
      'GAME_RECORD_TYPE'  => $GAME_RECORD_TYPE,
    ]);
  }

    /**
     *  @brief  : 用户管理-创建房间记录
     *  @return : page
     *  @details:
     */
  public function tableAction(){
      $conds = [];
      $order = [];
      $GAME_RECORD_TYPE = config('GAME_RECORD_TYPE');
      $CHANNELS   = $this->GetAdminChannel();
      $GAME_KIND  = GetGameKind();
      ////////////////////////////////////////////////////////////////////////////
      $Channel = $this->request->param('Channel/d', -1);
      if ($Channel > 0 && array_key_exists($Channel, $CHANNELS)) {
          $conds['b.Channel'][] = ['IN', array_keys($CHANNELS)];
          $conds['b.Channel'][] = ['EQ', $Channel];
      } else {
          $conds['b.Channel'] = ['IN', array_keys($CHANNELS)];
      }
      ///////////////////////////////////
      $KindID = $this->request->param('KindID/d', -1);
      if ($KindID > 0 && array_key_exists($KindID, $GAME_KIND)) {
          $conds['a.KindID'] = $KindID;
      }
      ///////////////////////////////////
      $time1 = $this->request->param('time1/s', '', 'trim');
      $time2 = $this->request->param('time2/s', '', 'trim');
      $aa = YmdHis2Unix($time1);
      $bb = YmdHis2Unix($time2);
      $ta = date('Y-m-d 00:00:00', $aa);
      $tb = date('Y-m-d 23:59:59', $bb);
      if ($aa > 0) {
          if ($bb > 0) {
              if ($aa <= $bb) {
                  $conds['a.CreateTime'] = ['BETWEEN TIME', [$ta, $tb]];
              } else {
                  $conds['a.CreateTime'] = ['>= TIME', $ta];
              }
          } else {
              $conds['a.CreateTime'] = ['>= TIME', $ta];
          }
      } else {
          if ($bb > 0) {
              $conds['a.CreateTime'] = ['<= TIME', $tb];
          }
      }
      ///////////////////////////////////
      $type = $this->request->param('type/d', -1);
      $type = array_key_exists($type, $GAME_RECORD_TYPE) ? $type : -1;
      if ($type != -1) {
          $conds['a.RecordType'] = $type;
      }
      ///////////////////////////////////
      $search = $this->request->param('search/s', '', 'trim');
      if (!empty($search)) {
          if (is_numeric($search) && $search > 0 && $search < PHP_INT_MAX) {
              $conds['a.UserID|b.GameID'] = $search;
          } else {
              $conds['b.NickName'] = ['LIKE', "%{$search}%"];
          }
      }
      ///////////////////////////////////
      $RoomID = $this->request->param('RoomID/d', 0);
      if ($RoomID > 0) {
          $conds['a.RoomCardID'] = $RoomID;
      }
      ////////////////////////////////////////////////////////////////////////////
      $order_map = [
          'A' => 'RecordID',
          'B' => 'Channel',
          'C' => 'KindID',
          'D' => 'ServerID',
          'E' => 'GameID',
          'F' => 'RoomCardID',
          'G' => 'RecordType',
          'H' => 'AddTime',

      ];
      $this->orderField = array_key_exists($this->orderField, $order_map) ? $this->orderField : 'A';
      $order[$order_map[$this->orderField]] = $this->orderDirection;
      ////////////////////////////////////////////////////////////////////////////
      $list = table('CYRecordDB.dbo.RecordCreateTable a', 'rydb.record')->field([
          'a.RecordID', 'a.UserID', 'a.RoomCardID', 'a.ServerID', 'e.ServerName',
          'a.KindID', 'd.GameName','a.Remork',
          'a.RecordType',  'a.RecordGroupID',
          'b.GameID', 'b.Accounts', 'b.NickName', 'b.PassPortID', 'b.Compellation',
          'b.Sex', 'b.RegisterIP', 'b.RegisterDate', 'b.LastLogonIP', 'b.LastLogonDate',
          'b.AccountsType', 'b.Channel', 'b.GameLogonCount',
          "ISNULL(b.RegisterMobile, '')" => 'MobilePhone',
          "ISNULL(b.AccountImgUrl, '')" => 'Avatar',
          'CONVERT(VARCHAR(19), a.CreateTime, 120)' => 'AddTime',
      ])
          ->join('CYBasicDB.dbo.AccountsInfo b',   'b.UserID = a.UserID', 'LEFT')
          ->join('CYBasicDB.dbo.GameKindItem d',   'd.KindID = a.KindID', 'LEFT')
          ->join('CYBasicDB.dbo.GameRoomInfo e',   'e.ServerID = a.ServerID', 'LEFT')
          ->where($conds)->order($order)
          ->paginate();

      ////////////////////////////////////////////////////////////////////////////
      return $this->fetch('', [
          'GAME_RECORD_TYPE' => $GAME_RECORD_TYPE,
          'CHANNELS'  => $CHANNELS,
          'GAME_KIND' => $GAME_KIND,
          'Channel'   => $Channel,
          'KindID'    => $KindID,
          'time1'     => $time1,
          'time2'     => $time2,
          'type'      => $type,
          'search'    => $search,
          'RoomID'    => $RoomID != 0 ? $RoomID : '',
          'list'      => $list,
      ]);
  }

}
